package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Bank;
import cn.imvc.app.repositories.BankRepository;
import cn.imvc.data.domain.ViewRequest;
@Service
public class BankModelImpl implements BankModel{

	@Autowired
	BankRepository bankRepository;
	
	public Page<Bank> find(ViewRequest viewRequest) {
		return bankRepository.findAll(viewRequest);
	}

	public Bank get(int id) {
		return bankRepository.getOne(id);
	}

	
	public int save(Bank bank) {
		
		String code = bank.getCode();
		String name = bank.getName();
		List<Bank> bc = bankRepository.getByCode(code);
		List<Bank> bn = bankRepository.getByName(name);
		if(bc.size()>0){
			return 0;
		}else if(bn.size()>0){
			return -1;
		}
		bankRepository.saveAndFlush(bank);
		return 1;
	}

	public int update(int id,Bank bank) {
		
		Bank loadBank = bankRepository.getOne(id);
		String code = bank.getCode();
		String name = bank.getName();
		List<Bank> bc = bankRepository.getByCode(code);
		List<Bank> bn = bankRepository.getByName(name);
		if(bc.size()>0&&!code.equals(loadBank.getCode())){
			return 0;
		}else if(bn.size()>0&&!name.equals(loadBank.getName())){
			return -1;
		}
		BeanUtils.copyProperties(bank, loadBank,new String[]{"id"});
		bankRepository.saveAndFlush(loadBank);
		return 1;
		
	}
	
	public void delete(int id) {
		
		bankRepository.delete(id);
	}
	
	public void deleteBatch(int[] ids) {
		
		for (int id : ids) {
			
			bankRepository.delete(id);
		}
	}




}
